package com.liyueheng.app.dataWarehouseDetail.portrait

import com.liyueheng.util.{ConfigLoader, SaveAsTable, SparkConf}
import org.apache.spark.sql.functions._

object AgePortrait {
  def analyzeAge(): Unit = {
    println("------------------ 分析年龄分布 -----------------")
    val spark = SparkConf.createSparkSession("AgePortrait")
    val dwd = ConfigLoader.getString("databases.dwd")
    val dws = ConfigLoader.getString("databases.dws")

    val df = spark.table(s"$dwd.user")
      .withColumn("age", datediff(current_date(), to_date(col("birthday"))) / 365)
      .withColumn("age_group",
        when(col("age").between(0, 2), "婴幼儿(0-2岁)")
          .when(col("age").between(3, 6), "儿童(3-6岁)")
          .when(col("age").between(7, 14), "少年(7-14岁)")
          .when(col("age").between(15, 35), "青年(15-35岁)")
          .otherwise("未知")
      )
      .groupBy("age_group")
      .count()
      .withColumnRenamed("age_group", "name")
      .withColumnRenamed("count", "value")

    SaveAsTable.saveAsTable(df, s"$dws.detail_age_portrait")
    SparkConf.stopSparkSession(spark)
  }
}
